'use strict';

module.exports = function (UploadedFile) {
  // 文件上传端点
  UploadedFile.upload = function (req, res, cb) {
    const containerName = 'uploads';

    // 创建存储容器（如果不存在）
    UploadedFile.app.models.Container.getContainer(containerName, function (err, container) {
      if (err) {
        UploadedFile.app.models.Container.createContainer({ name: containerName }, function (err, container) {
          if (err) return cb(err);
          uploadFile(req, res, containerName, cb);
        });
      } else {
        uploadFile(req, res, containerName, cb);
      }
    });
  };

  // 文件下载端点
  UploadedFile.download = function (id, res, cb) {
    UploadedFile.findById(id, function (err, file) {
      if (err || !file) return cb(err || new Error('File not found'));

      // 通过容器下载文件
      UploadedFile.app.models.Container.download(file.container, file.name, res, function (err) {
        if (err) return cb(err);
        cb();
      });
    });
  };

  // 辅助函数：处理文件上传
  function uploadFile(req, res, containerName, cb) {
    UploadedFile.app.models.Container.upload(req, res, { container: containerName }, function (err, fileObj) {
      if (err) return cb(err);

      const fileInfo = fileObj.files.file[0];
      const fileData = {
        name: fileInfo.name,
        type: fileInfo.type,
        container: containerName,
        size: fileInfo.size,
      };

      // 保存文件元数据到模型
      UploadedFile.create(fileData, function (err, file) {
        if (err) return cb(err);
        cb(null, file);
      });
    });
  }

  // 注册远程方法
  UploadedFile.remoteMethod(
    'upload',
    {
      description: 'Upload a file',
      accepts: [
        { arg: 'req', type: 'object', 'http': { source: 'req' } },
        { arg: 'res', type: 'object', 'http': { source: 'res' } },
      ],
      returns: { arg: 'fileObject', type: 'object', root: true },
      http: { path: '/upload', verb: 'post' },
    }
  );

  UploadedFile.remoteMethod(
    'download',
    {
      description: 'Download a file',
      accepts: [
        { arg: 'id', type: 'string', required: true },
        { arg: 'res', type: 'object', 'http': { source: 'res' } },
      ],
      returns: {},
      http: { path: '/:id/download', verb: 'get' },
    }
  );
};
